###
	Outline
	
	- Global Vars
	- Core Code (run once)
		-- add table / form
		-- self subscription (duplicate check)
		-- main subscription (fill form)
	- Event Handlers
		-- cancel button
		-- submit button
			-- check duplicate
			-- check invalid fields
			-- doc obj and parse
			-- save doc to couch
				-- publish Donor ID
###

define [
	'jquery'
	'helper'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->
	S = {}

	# Custom Date() helper function to output ISODate Format (YYYY-MM-DD HH:MM:SS)
	Date.prototype.isoDateTime = ->
		yyyy = @getUTCFullYear()
		mm = @getUTCMonth() + 1
		mm = "0#{mm}" if mm < 10
		dd = @getUTCDate()
		dd = "0#{dd}" if dd < 10
		hhmmss = @toTimeString().split('GMT')[0]
		hhmmss = hhmmss.slice 0, hhmmss.length - 1
		"#{yyyy}-#{mm}-#{dd} #{hhmmss}"

	$.fn.mb_add_donation = (SamCtx) ->

		# --- Global Variables and Function ---------------
		$this = $(ins = @)
		_time = donorID = defaultAmount = savedAmount = ''
		S = SamCtx
		$tbody = $('tbody', @)

		# --- Core code of plugin -------------------------

		unless @mb_plugin()
			@mb_plugin 'add_donation'

			# Self-subscription of donation ID to retrieve "last-created" donation doc date so that
			# subsequent matching of date can be tested to avoid duplicate donation creation
			$.subscribe 'mb.donation', (e, arg) =>
				H.db().openDoc arg['id'],
					success: (doc) ->
						_time = doc.donation_date if arg['ok']

			# Main subscription event to handle a donor_id being published from donor_detail
			$.subscribe 'mb.add_donation', (e, arg) =>
				donorID = arg['donor_id']
				defaultAmount = arg['amount']

				# Clone a copy of the saved tbody form
				$form = $tbody.clone()
				# Remove elements based on "ind" or "org" classes
				$form.find(".field:not(#{arg['class1']})").remove()
				# Remove secondary elements if in "ind" class, class2 is either ".all" or ".family"
				$form.find('.field.ind:not(.all)').remove() if arg['class2'] is '.all'
				# Add this form to our table
				$('table', @).empty().append($form)
				# Empty all manually input fields to empty form
				$('[name="reset"]', @).click()

		$('table', @).on 'focus', '[name="donation_amount"]', ->
			savedAmount = $(@).val()
			$(@).val savedAmount.replace /[$]|\.00/g, ''

		$('table', @).on 'blur', '[name="donation_amount"]', ->
			# Helper error handling when field is invalidated
			# When invalidation occurs, the textbox is formatted to last saved appropriate value
			# and the textbox is selected so user will have to input something valid
			err = (msg, $this) ->
				$this.val(savedAmount).select()
				$.publish 'mb.msg',
					msg: msg
					type: 'error'

			# Error checking
			# Keep a copy of the current value
			old_val = $(@).val()
			if old_val is ''
				err 'Donation Amount cannot be empty', $(@)
				return false
			if isNaN(old_val) or old_val < 0
				err 'Donation amount is not a number.', $(@)
				return false
			if old_val.indexOf('.') isnt -1
				if old_val.split('.').length > 2 or old_val.split('.')[1] isnt '00'
					err 'Donation amount is not valid.', $(@)
					return false

			# Error check passed, remove $ signs and ".00" if user manually input into the
			# field, then append $ and ".00" automatically
			new_val = old_val.replace /[$]|\.00/g, ''
			$(@).val "$#{new_val}.00"
			return false

		# --- Button Event Handlers ------------------

		@on 'click', '[name="cancel"]', -> S.setLocation "#/donor_detail"

		# Refresh button updates the time
		@on 'click', '[name="refresh"]', ->
			dv = (new Date()).isoDateTime()
			$('[name="donation_date"]').val(dv).html(dv)

		# Reset button resets form to default values
		@on 'click', '[name="reset"]', =>
			$('[type="text"], textarea', @).each -> $(@).val ''
			$('[name="refresh"]', @).click()
			$('[name="donation_amount"]', @).val(defaultAmount)
			$('[name="donor_id"]', @).val(donorID)
			return false

		@on 'click', '[name="submit"]', (e) ->

			# Check to see for duplicate creation
			if _time isnt ""
				if $("[name='donation_date']", ins).val().toString() is _time.toString()
					$.publish "mb.msg",
						msg: "Duplicate donation. Refresh Payment Date field to add new donation."
						type: "error"
					return false

			# Check to see for empty Donation Amount field
			if $('[name="donation_amount"]', ins).val().length is 0
				$.publish "mb.msg",
					msg: "Donation amount field cannot be empty."
					type: "error"
				return false

			$('[name="donation_amount"]', ins).select()

			# Create helper doc object and parse the serializeArray of the form
			(doc = new H.doc).parse $('form', ins).serializeArray()
			doc.cash or= false

			# Save object to couch document
			H.db().saveDoc doc,
				success: (save) ->

					# Publish donation detail (ie. ID) for donation_detail is subscribed to
					$.publish "mb.donation", save

					$('[name="donation_amount"]', ins).blur()

					# Publish to "mb.donor" to let view_receipt know that it should refresh its
					# record table only when donation has been added successfully
					if save.ok
						$.publish "mb.donor", donor_id: donorID
						S.setLocation "#/donation_detail"

			return false
		return @
	return
